import { currentData } from "./currentdata";
import { project } from "./project";
import * as path from 'path'
import * as electron from 'electron'
import * as fs from 'fs';




type MapItem = { x: number, y: number, tile: string, npc: number, item: number }

class MapPropertyContainer {

    root: HTMLElement;

    tileSelector: HTMLSelectElement;
    npcSelector: HTMLSelectElement;

    constructor(private mapEditor: MapEditor) {
        this.root = document.createElement("div");

        // this.root.innerHTML = "属性编辑2";

        const defaultPath = project.projectRoot;



        const textureSelectSpan = document.createElement("span");
        const data = currentData.getCurrentData();
        textureSelectSpan.innerHTML = "地形"

        const textureSelect = document.createElement("select");

        for (let option of data.map[0].tileType) {
            const option1 = document.createElement("option");
            option1.value = option;
            option1.innerText = option;
            textureSelect.appendChild(option1)




            //图片选择

            const tileTypeDescription = document.createElement("span");
            tileTypeDescription.innerHTML = option + "图片";
            this.root.appendChild(tileTypeDescription);



            const tileTypeImage = document.createElement("img");
            if (option == "TREE") {

                tileTypeImage.src = defaultPath + '/' + data.map[0].treeTexture;
                tileTypeImage.id = "1";
            }
            else if (option == "GRASS") {
                tileTypeImage.src = defaultPath + '/' + data.map[0].grassTexture;
                tileTypeImage.id = "2";
            }



            //改图片
            tileTypeImage.onclick = () => {
                const defaultPath = project.projectRoot;
                electron.remote.dialog.showOpenDialog({
                    title: "select image",
                    defaultPath,
                    filters: [
                        { name: 'Images', extensions: ['jpg', 'png', "jpeg"] }
                    ]
                }, (filenames) => {
                    if (filenames) {

                        const filename = filenames[0];
                        tileTypeImage.src = filename;
                        const relativePath = path.relative(defaultPath, filename).split("\\").join("/");

                        //改地图
                        if (tileTypeImage.id == "1") {
                            data.map[0].treeTexture = relativePath;
                        }
                        else if (tileTypeImage.id == "2") {
                            data.map[0].grassTexture = relativePath;
                        }




                        // console.log(currentData);

                        //      currentData.saveAndReload();
                        // console.log(currentData);
                        this.mapEditor.update();
                    }

                })

            }

            this.root.appendChild(tileTypeImage);
        }


        const addTile = document.createElement("div");
        const editNpc = document.createElement("div");

        const addTileTypeSpan = document.createElement("span");
        addTileTypeSpan.innerHTML = "添加地图种类";
        const addTileType = document.createElement("input");
        const addTileTypeButton = document.createElement("button");
        addTileTypeButton.innerHTML = "添加";
        addTileTypeButton.innerText = "添加";

        addTileTypeButton.onclick = () => {
            const newTile = addTileType.value;
            console.log(newTile);

            data.map[0].tileType.push(newTile);
            //  currentData.saveAndReload();
            this.mapEditor.update();
        }


        //NPC

        const npcSelect = document.createElement("select");
        const npcSelectSpan = document.createElement("span")
        npcSelectSpan.innerHTML = "NPC";


        const npcFile = "npc.json";
        const npcFilename = path.join(project.projectRoot, npcFile)
        const prefix = 'npc';

        const content = fs.readFileSync(npcFilename, 'utf-8');
        const json = JSON.parse(content);
        const npcs = json[prefix];

        for (let npc of npcs) {
            const option1 = document.createElement("option");
            option1.value = npc.id.toString();
            option1.innerText = npc.name;
            npcSelect.appendChild(option1)
        }


        const option2 = document.createElement("option");
        option2.value = "0";
        option2.innerText = "无";
        npcSelect.appendChild(option2)

        editNpc.appendChild(npcSelectSpan);
        editNpc.appendChild(npcSelect);



        this.root.appendChild(textureSelectSpan);
        this.root.appendChild(textureSelect);
        this.root.appendChild(editNpc);



        addTile.appendChild(addTileTypeSpan);
        addTile.appendChild(addTileType);
        addTile.appendChild(addTileTypeButton);

        this.root.appendChild(addTile)


        this.tileSelector = textureSelect;
        this.npcSelector = npcSelect;
    }

    setItem(item: MapItem) {
        this.tileSelector.value = item.tile.toString();
        this.tileSelector.onchange = () => {
            item.tile = this.tileSelector.value;


            //   currentData.saveAndReload();
            this.mapEditor.update();

        }

        //npc
        if (item.npc) {
            this.npcSelector.value = item.npc.toString();
        } else {
            this.npcSelector.value = "0";
        }

        this.npcSelector.onchange = () => {
            item.npc = parseInt(this.npcSelector.value);


            //    currentData.saveAndReload();
            this.mapEditor.update();

        }


    }


}


export class MapEditor {


    constructor(private root: HTMLElement) {

    }

    update() {
        currentData.saveAndReload();
        this.root.innerHTML = "";
        this.show();


    }


    show() {

        const data = currentData.getCurrentData();

        const config = data.map[0].mapSetting;
        const TILE_SIZE = 64;
        const defaultPath = project.projectRoot;


        for (let item of config) {

            const img = document.createElement("img");
            let imgUrl = ""
            switch (item.tile) {
                case "TREE":
                    imgUrl = data.map[0].treeTexture;
                    break;
                case "GRASS":
                    imgUrl = data.map[0].grassTexture;
                    break;
                default:
                    alert("错误的地图配置!!" + JSON.stringify(item))
                    break;
            }
            img.src = path.join(project.projectRoot, imgUrl);
            img.onclick = () => {
                mapPropertyContainer.setItem(item);
            }



            const npcImg = document.createElement("img");
            let npcImgUrl = ""

            const npcFile = "npc.json";
            const npcFilename = path.join(project.projectRoot, npcFile)
            const prefix = 'npc';
            const content = fs.readFileSync(npcFilename, 'utf-8');
            const json = JSON.parse(content);
            const npcs = json[prefix];

            for (let npc of npcs) {
                if (item.npc == npc.id) {
                    npcImgUrl = npc.avatar;
                    npcImg.src = path.join(project.projectRoot, npcImgUrl);
                    console.log(npcImg.src);

                }

            }
            npcImg.onclick = () => {
                mapPropertyContainer.setItem(item);
            }


            this.root.appendChild(img);
            this.root.appendChild(npcImg)

            setPosition(img, TILE_SIZE * item.x, TILE_SIZE * item.y);
            setPosition(npcImg, TILE_SIZE * item.x, TILE_SIZE * item.y);
        }
        const mapPropertyContainer = new MapPropertyContainer(this);
        this.root.appendChild(mapPropertyContainer.root);
        setPosition(mapPropertyContainer.root, 0, 520)
    }

    hide() {
        this.root.innerHTML = "";
    }

}

function setPosition(node: HTMLElement, x: number, y: number) {

    const parent = node.parentElement;
    if (parent) {
        const newX = parent.offsetLeft + x;
        const newY = parent.offsetTop + y;
        node.style.position = "absolute";
        node.style.left = newX + "px";
        node.style.top = newY + "px";
    }



}